/*
 * Copyright 2008-2009 Sanjay Dwivedi.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.isdinvestments.common.repository;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class HibernateDao<T extends Object> extends AbstractDao<T> implements Dao<T> {
	@Autowired
	private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}
	
	public void persist(T t) {
		getSession().save(t);
	}
	
	@SuppressWarnings("unchecked")
	public T get(Long id) {
		return (T) getSession().get(getDomainClass(), id);
	}
	
	@SuppressWarnings("unchecked")
	public T getReference(Long id) {
		return (T) getSession().load(getDomainClass(), id);
	}
	
	@SuppressWarnings("unchecked")
	public List<T> getList() {
		Query q = getSession().createQuery("from " + getDomainClassName());
		return q.list();
	}
	
	public void update(T t) {
		getSession().update(t);
	}
	
	public void delete(T t) {
		getSession().delete(t);
	}
	
	public void deleteById(Long id) {
		getSession().delete(getReference(id));
	}
	
	public void deleteAll() {
		Query q = getSession().createQuery("delete " + getDomainClassName());
		q.executeUpdate();
	}
	
	public long count() {
		Query q = getSession()
			.createQuery("select count(*) from " + getDomainClassName());
		return (Long) q.uniqueResult();
	}
}
